package com.zbkj.crmeb.merchant.admin.service.impl;

import com.constants.Constants;
import com.utils.CrmebUtil;
import com.utils.DateUtil;
import com.zbkj.crmeb.enums.IdentityTypeEnum;
import com.zbkj.crmeb.merchant.admin.service.MerAgentHomePageService;
import com.zbkj.crmeb.statistics.response.HomeRateResponse;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 服务商-控制台 服务实现类
 *
 * @author lvmd
 * @date 2022-02-18
 */
@Service
@Slf4j
public class MerAgentHomePageServiceImpl implements MerAgentHomePageService {

    @Autowired
    private UserService userService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Resource
    private SystemAdminService systemAdminService;

    /**
     * 销售额
     *
     * @param merIds
     * @return
     * @author lvmd
     * @date 2022-02-18
     */
    @Override
    public HomeRateResponse sales(List<Integer> merIds) {
        //今日销售额
        BigDecimal today = storeOrderInfoService.getSumBigDecimalByMerIds(Constants.SEARCH_DATE_DAY, merIds);
        //昨天销售额
        BigDecimal yesterday = storeOrderInfoService.getSumBigDecimalByMerIds(Constants.SEARCH_DATE_YESTERDAY, merIds);
        //总销售额
        BigDecimal all = storeOrderInfoService.getSumBigDecimalByMerIds(null, merIds);
        //同比公式 即：同比增长率=（本年的指标值-去年同期的值）/ 去年同期的值 * 100%
        BigDecimal dayRate = CrmebUtil.getRateDecimal(today, yesterday);
        return new HomeRateResponse(today, yesterday, dayRate + "%", null, all);
    }

    /**
     * 订单量
     *
     * @param merIds
     * @return
     * @author lvmd
     * @date 2022-02-18
     */
    @Override
    public HomeRateResponse orders(List<Integer> merIds) {
        ///今日数量
        int todayChild = storeOrderInfoService.countChildOrderByMerIds(Constants.SEARCH_DATE_DAY, merIds);
        //昨日数量
        int yesterdayChild = storeOrderInfoService.countChildOrderByMerIds(Constants.SEARCH_DATE_YESTERDAY, merIds);
        //总数量
        int all = storeOrderInfoService.countChildOrderByMerIds(null, merIds);
        //日同比
        BigDecimal dayRateDecimal = CrmebUtil.getRateDecimal(todayChild, yesterdayChild);
        return new HomeRateResponse(todayChild, yesterdayChild, dayRateDecimal + "%", null, all);
    }

    /**
     * 用户曲线图
     */
    @Override
    public Map<Object, Object> chartUser(List<Integer> merIds) {
        return dataFormat(userService.countAddUserGroupDateByMerIds(Constants.SEARCH_DATE_LATELY_30, merIds), Constants.SEARCH_DATE_LATELY_30);
    }

    /**
     * 订单量趋势
     *
     */
    @Override
    public Map<String, Object> chartOrder(List<Integer> merIds, String type) {
        Map<String, Object> map = new HashMap<>();
        String preDateLimit = Constants.SEARCH_DATE_PRE_WEEK;
        int lefTime = Constants.NUM_TEN;
        switch (type) {
            case Constants.SEARCH_DATE_WEEK:
                preDateLimit = Constants.SEARCH_DATE_PRE_WEEK;
                break;
            case Constants.SEARCH_DATE_MONTH:
                preDateLimit = Constants.SEARCH_DATE_PRE_MONTH;
                break;
            case Constants.SEARCH_DATE_YEAR:
                preDateLimit = Constants.SEARCH_DATE_PRE_YEAR;
                lefTime = Constants.NUM_SEVEN;
                break;
            default:
//                preDateLimit = Constants.SEARCH_DATE_PRE_WEEK;
        }

        // 年
        List<StoreOrderInfo> childOrderList = storeOrderInfoService.sumChildOrderGroupByDate(type, lefTime, merIds);
        if (Constants.SEARCH_DATE_YEAR.equals(type)) {
            map.put("quality",
                    dataFormatYear(getChildOrderCountGroupByDate(childOrderList), type)
            );
            map.put("price",
                    dataFormatYear(getChildOrderPriceGroupByDate(childOrderList), type)
            );
            List<StoreOrderInfo> preStoreOrderInfoList = storeOrderInfoService.sumChildOrderGroupByDate(type, lefTime, merIds);
            map.put("preQuality",
                    dataFormatYear(getChildOrderCountGroupByDate(preStoreOrderInfoList), preDateLimit)
            );
            map.put("prePrice",
                    dataFormatYear(getChildOrderCountGroupByDate(preStoreOrderInfoList), preDateLimit)
            );
            return map;
        }

        map.put("quality",
                dataFormat(getChildOrderCountGroupByDate(childOrderList), type)
        );
        map.put("price",
                dataFormat(getChildOrderPriceGroupByDate(childOrderList), type)
        );

        if (!Constants.SEARCH_DATE_LATELY_30.equals(type)){
            List<StoreOrderInfo> preStoreOrderInfoList = storeOrderInfoService.sumChildOrderGroupByDate(type, lefTime, merIds);
            map.put("preQuality",
                    dataFormat(getChildOrderCountGroupByDate(preStoreOrderInfoList), preDateLimit)
            );
            map.put("prePrice",
                    dataFormat(getChildOrderCountGroupByDate(preStoreOrderInfoList), preDateLimit)
            );
        }
        return map;
    }

    /**
     * 日期和数量格式化
     * @author Mr.Zhang
     * @since 2020-05-16
     * @return Map<String, Integer>
     */
    private Map<Object, Object> dataFormatYear(Map<Object, Object> countGroupDate, String dateLimit){
        Map<Object, Object> map = new LinkedHashMap<>();
        List<Object> listDate = new ArrayList<>();
        String year = "";
        if(dateLimit.equals(Constants.SEARCH_DATE_YEAR)) {
            year = DateUtil.nowYear();
        }

        if(dateLimit.equals(Constants.SEARCH_DATE_PRE_YEAR)) {
            year = DateUtil.lastYear();
        }

        //处理年
        //12个月份数据
        for (int i = 1; i <= 12; i++){
            String month = i + "";
            if(i < 10){
                month = "0" + i;
            }
            listDate.add(year + "-" + month);
        }

        String[] monthList = new String[]{"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月" , "十一月", "十二月" };

        int i = 0;
        for (Object date : listDate) {
            Object count = 0;
            if(countGroupDate.containsKey(date)){
                count = countGroupDate.get(date);
            }
            map.put(monthList[i], count);
            i++;
        }
        return map;
    }

    /**
     * 净利润
     *
     * @param merIds
     * @return
     */
    @Override
    public HomeRateResponse profit(List<Integer> merIds) {
        SystemAdmin systemAdmin = systemAdminService.getInfo();
        String field = "";
        if (IdentityTypeEnum.AGENCY_ONE.getCode().equals(systemAdmin.getIdentityType())) {
            field = "first_agent_profit";
        } else if (IdentityTypeEnum.AGENCY_TWO.getCode().equals(systemAdmin.getIdentityType())) {
            field = "second_agent_profit";
        } else {
            return new HomeRateResponse(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO + "%", null, BigDecimal.ZERO);
        }
        // 今日净利润
        BigDecimal today = storeOrderInfoService.getSumProfitBigDecimal(Constants.SEARCH_DATE_DAY, merIds, field);
        // 昨天净利润
        BigDecimal yesterday = storeOrderInfoService.getSumProfitBigDecimal(Constants.SEARCH_DATE_YESTERDAY, merIds,field);
        // 总净利润
        BigDecimal all = storeOrderInfoService.getSumProfitBigDecimal(null, merIds,field);
        // 同比公式 即：同比增长率=（本年的指标值-去年同期的值）/ 去年同期的值 * 100%
        // 日同比
        BigDecimal dayRate = CrmebUtil.getRateDecimal(today, yesterday);
        return new HomeRateResponse(today, yesterday, dayRate + "%", null, all);

    }

    private Map<Object, Object> getChildOrderCountGroupByDate(List<StoreOrderInfo> list) {
        Map<Object, Object> map = new HashMap<>();

        if (list.size() < 1) {
            return map;
        }

        for (StoreOrderInfo storeOrderInfo : list) {
            map.put(storeOrderInfo.getChildOrderNumber(), storeOrderInfo.getId());
        }

        return map;
    }

    private Map<Object, Object> getChildOrderPriceGroupByDate(List<StoreOrderInfo> list) {
        Map<Object, Object> map = new HashMap<>();
        if (list.size() < 1) {
            return map;
        }
        for (StoreOrderInfo storeOrderInfo : list) {
            map.put(storeOrderInfo.getChildOrderNumber(), storeOrderInfo.getPayPrice());
        }
        return map;
    }

    /**
     * 日期和数量格式化
     */
    private Map<Object, Object> dataFormat(Map<Object, Object> countGroupDate, String dateLimit) {
        Map<Object, Object> map = new LinkedHashMap<>();
        List<String> listDate = DateUtil.getListDate(dateLimit);

        String[] weekList = new String[]{"周一", "周二", "周三", "周四", "周五", "周六", "周日"};

        int i = 0;
        for (String date : listDate) {
            Object count = 0;
            if (countGroupDate.containsKey(date)) {
                count = countGroupDate.get(date);
            }
            String key;

            //周格式化
            switch (dateLimit) {
                //格式化周
                case Constants.SEARCH_DATE_WEEK:
                case Constants.SEARCH_DATE_PRE_WEEK:
                    key = weekList[i];
                    break;
                //格式化月
                case Constants.SEARCH_DATE_PRE_MONTH:
                case Constants.SEARCH_DATE_MONTH:
                    key = i + 1 + "";
                    break;
                //默认显示两位日期
                default:
                    key = date.substring(5, 10);
            }
            map.put(key, count);
            i++;
        }
        return map;
    }

    /**
     * 用户购买统计
     *
     * @param merIds
     * @return
     */
    @Override
    public Map<String, Integer> chartUserBuy(List<Integer> merIds) {
        Map<String, Integer> map = new HashMap<>();
        //未消费用户
        map.put("zero", userService.countPayUserByMerIds(Constants.NUM_ZERO, Constants.NUM_ZERO, merIds));

        //消费一次用户
        map.put("one", userService.countPayUserByMerIds(Constants.NUM_ONE, Constants.NUM_ONE, merIds));

        //留存客户
        map.put("history", userService.countPayUserByMerIds(Constants.NUM_TWO, Constants.NUM_THREE, merIds));

        //回流客户
        map.put("back", userService.countPayUserByMerIds(Constants.NUM_ONE, Constants.EXPORT_MAX_LIMIT, merIds));

        return map;
    }

    /**
     * 组装订单统计返回数据
     *
     * @param dateLimit
     * @param preDateLimit
     * @param leftTime
     * @param merIds
     * @return
     */
    private Map<String, Object> returnOrderDate(String dateLimit, String preDateLimit, int leftTime, List<Integer> merIds) {
        Map<String, Object> map = new HashMap<>();

        //查询本周周订单量
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.sumChildOrderGroupByDate(dateLimit, leftTime, merIds);
        map.put("quality",
                dataFormat(getChildOrderCountGroupByDate(storeOrderInfoList), dateLimit)
        );
        map.put("price",
                dataFormat(getChildOrderCountGroupByDate(storeOrderInfoList), dateLimit)
        );

        //查询上周周订单量
        List<StoreOrderInfo> preStoreOrderInfoList = storeOrderInfoService.sumChildOrderGroupByDate(dateLimit, leftTime, merIds);

        map.put("preQuality",
                dataFormat(getChildOrderCountGroupByDate(preStoreOrderInfoList), preDateLimit)
        );
        map.put("prePrice",
                dataFormat(getChildOrderCountGroupByDate(preStoreOrderInfoList), preDateLimit)
        );

        return map;
    }

}
